<?php
/**
 * orders.php
 * User: yzm
 * Date: 2017/8/24
 */

class Orders extends WebBase{

    /*
     * 工单列表
     */
    public function index() {
        global $_W,$_GPC;

        if ($_W['isajax']) {

            $order_status = !empty($_GPC['order_status']) ? $_GPC['order_status'] : 0;
            $where_sql = ' WHERE `uniacid`=:uniacid AND `order_status` = ' . $order_status . ' AND `belong_to` = 0 ';
            $where[':uniacid'] = $_W['uniacid'];

            $sortOrder = !empty($_GPC['sortOrder']) ? $_GPC['sortOrder'] : 'desc';
            $sortName = !empty($_GPC['sortName']) ? $_GPC['sortName'] : 'update_time DESC, add_time ';

            //搜索-分类
            if (!empty($_GPC['cat_id'])) {
                //查询当下有没有子分类
                $where_sql .= " AND `cat_id` = " . $_GPC['cat_id'];
            }
            //搜索-单号/客户名
            if (!empty($_GPC['search_name'])) {
                $where_sql .= " AND (`order_sn` LIKE :search_name  OR `nickname` LIKE :search_name) ";
                $where[':search_name'] = '%' . $_GPC['search_name'] . '%';
            }
            //搜索-时间
            if (!empty($_GPC['begin_time'])) {
                $begin_time = !empty($_GPC['begin_time']) ? strtotime($_GPC['begin_time']) : '';
                $where_sql .= " AND `add_time` >= " . $begin_time;
            }
            if (!empty($_GPC['end_time'])) {
                $end_time = !empty($_GPC['end_time']) ? strtotime($_GPC['end_time']) + + 24 * 60 * 60 : '';
                $where_sql .= " AND `add_time` <= " . $end_time;
            }

            $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('wherein_knowledge_work_order') . $where_sql, $where);

            $list = pdo_fetchall("SELECT * FROM ".tablename('wherein_knowledge_work_order') . $where_sql . " ORDER BY " . $sortName . " " . $sortOrder . " LIMIT " . $_GPC['offset'] . ", " . $_GPC['limit'], $where);
            if (!empty($list)) {
                load()->model('mc');
                foreach ($list as $key => $value) {
                    $list[$key]['order_status_name'] = $this->order_status[$value['order_status']];
                    $list[$key]['customer_status_name'] = $this->customer_status[$value['customer_status']];
                    $list[$key]['add_time'] = format($value['add_time']);
                    $list[$key]['update_time'] = !empty($value['update_time']) ? format($value['update_time']) : '-';
                    $user = mc_fansinfo($value['openid']);
                    $list[$key]['avatar'] = !empty($user['avatar']) ? $user['avatar'] : NO_AVATAR;
                }
            }

            $out['total'] = $total;
            $out['rows'] = $list;
            $this->outjson($out);
        }

        include $this->template('index');
    }

    /*
     * 获取工单数据
     */
    public function getEditWorkOrder() {
        global $_W,$_GPC;
        $order_id = !empty($_GPC['order_id']) ? $_GPC['order_id'] : 0;
        if (empty($order_id)) {
            $this->outjson(array('code' => 404, 'msg' => '参数错误'));
        }
        //获取工单数据
        $order_data = pdo_get('wherein_knowledge_work_order', array('uniacid' => $_W['uniacid'], 'order_id' => $order_id, 'belong_to' => 0, 'parent_id' => 0), array('order_id', 'parent_id', 'cat_id', 'child_cat_id', 'openid', 'nickname', 'content', 'pic', 'add_time', 'order_status', 'customer_status', 'is_reply'));
        if (empty($order_data)) {
            $this->outjson(array('code' => 404, 'msg' => '找不到可编辑的数据'));
        }
        $order_data['cat_name'] = pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $order_data['cat_id']), 'cat_name');
        $order_data['child_cat_name'] = empty($order_data['child_cat_id']) ? '' : pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $order_data['child_cat_id']), 'cat_name');
        load()->model('mc');
        $user = mc_fansinfo($order_data['openid']);
        $order_data['avatar'] = !empty($user['avatar']) ? $user['avatar'] : NO_AVATAR;
        $order_data['add_time'] = format($order_data['add_time'], 'Y-m-d H:i');
        $order_data['customer_status_name'] = $this->customer_status[$order_data['customer_status']];

        //获取用户最新提问的消息
        $new_answer_data = pdo_fetch("SELECT content,add_time,pic FROM " . tablename('wherein_knowledge_work_order') . " WHERE belong_to = :belong_to AND is_reply = :is_reply ORDER BY order_id DESC ", array(':belong_to' => $order_data['order_id'], ':is_reply' => 0));
        $order_data['new_content'] = !empty($new_answer_data) ? $new_answer_data['content'] : $order_data['content'];
        $order_data['new_add_time'] = !empty($new_answer_data) ? format($new_answer_data['add_time'], 'Y-m-d H:i') : $order_data['add_time'];
        if (!empty($new_answer_data['pic'])) {
            $order_data['new_pic'] = explode(IMG_IMPLODE, $new_answer_data['pic']);
            foreach ($order_data['new_pic'] as $k=>$v) {
                $order_data['new_pic'][$k] = tomedia($v);
            }
        } else {
            $order_data['new_pic'] = array();
            if (!empty($order_data['pic'])) {
                $order_data['new_pic'] = explode(IMG_IMPLODE, $order_data['pic']);
                foreach ($order_data['new_pic'] as $k=>$v) {
                    $order_data['new_pic'][$k] = tomedia($v);
                }
            }
        }


        $order_list = array();
        $order_list[] = array(
            'order_id' => $order_data['order_id'],
            'belong_to' => 0,
            'parent_id' => $order_data['parent_id'],
            'openid' => $order_data['openid'],
            'nickname' => $order_data['nickname'],
            'content' => $order_data['content'],
            'pic' => $order_data['pic'],
            'add_time' => $order_data['add_time'],
            'is_reply' => $order_data['is_reply'],
        );

        //查询相关的工单回复信息
        $order_reply_list = pdo_fetchall("SELECT order_id,belong_to,parent_id,openid,nickname,content,pic,add_time,is_reply FROM " . tablename('wherein_knowledge_work_order') . " WHERE belong_to = :belong_to ORDER BY order_id asc", array(':belong_to' => $_GPC['order_id']));
        if (!empty($order_reply_list)) {
            foreach ($order_reply_list as $key => $value) {
                $value['add_time'] = format($value['add_time'], 'Y-m-d H:i');
                $order_list[] = $value;
            }
        }
        foreach ($order_list as $key => $value) {
            $user = mc_fansinfo($value['openid']);
            $order_list[$key]['avatar'] = !empty($user['avatar']) ? $user['avatar'] : NO_AVATAR;
            $order_list[$key]['content'] = htmlspecialchars_decode($value['content']);
            $order_list[$key]['pic'] = array();
            if (!empty($value['pic'])) {
                $order_list[$key]['pic'] = explode(IMG_IMPLODE, $value['pic']);
                foreach ($order_list[$key]['pic'] as $k=>$v) {
                    $order_list[$key]['pic'][$k] = tomedia($v);
                }
            }
        }

        $out['code'] = 200;
        $out['info'] = $order_data;
        $out['order_list'] = $order_list;
        $this->outjson($out);
    }

    /*
     * 发送回复工单
     *
     */
    public function reply() {
        global $_GPC,$_W;
        //获取工单数据
        $order_data = pdo_get('wherein_knowledge_work_order', array('order_id' => $_GPC['order_id'], 'parent_id' => 0), array('order_id', 'parent_id', 'cat_id', 'child_cat_id', 'openid', 'nickname', 'add_time', 'reply_num', 'order_status', 'customer_status'));
        if (empty($order_data)) {
            $this->outjson(array('code' => 404, 'msg' => '找不到数据'));
        }
        if ($order_data['customer_status'] == 2) {
            $this->outjson(array('code' => 500, 'msg' => '发送失败: 该工单在等待客户反馈'));
        }
        $parent_id = pdo_fetchcolumn("SELECT order_id FROM " . tablename('wherein_knowledge_work_order') . " WHERE belong_to = :belong_to AND is_reply = :is_reply ORDER BY order_id DESC ", array(':belong_to' => $_GPC['order_id'], ':is_reply' => 0));

        $data = array();
        $data['order_sn'] = create_order_sn();
        $data['uniacid'] = $_W['uniacid'];
        $data['belong_to'] = $_GPC['order_id'];
        $data['parent_id'] = $parent_id ? $parent_id : $order_data['order_id'];
        $data['cat_id'] = $order_data['cat_id'];
        $data['child_cat_id'] = $order_data['child_cat_id'];
        if (isset($_GPC['system_type']) && !empty($_GPC['system_type'])) {
            $data['openid'] = isset($_SESSION['userinfo']) && !empty($_SESSION['userinfo']) ? $_SESSION['userinfo']['openid'] : '';
            $data['nickname'] = isset($_SESSION['userinfo']) && !empty($_SESSION['userinfo']) ? $_SESSION['userinfo']['nickname'] : 'admin';
        } else {
            $data['openid'] = '';
            $data['nickname'] = 'admin';
        }
        $data['content'] = htmlspecialchars(strip_tags($_GPC['content']));
        $data['pic'] = '';
        $data['add_time'] = $_W['timestamp'];
        $data['is_reply'] = 1;

        if (pdo_insert('wherein_knowledge_work_order', $data)) {
            $reply_id = pdo_insertid();
            $expire_time = $_W['timestamp'] + 7 * 24 * 60 * 60;//七天后的过期时间
            if (!pdo_update('wherein_knowledge_work_order', array('expire_time' => $expire_time, 'reply_num' => intval($order_data['reply_num'])+1, 'customer_status' => 2, 'order_status' => 2, 'is_read' => 0), array('order_id' => $_GPC['order_id']))) {
                //如果更新失败,则删除回复数据
                pdo_delete('wherein_knowledge_work_order', array('order_id' => $reply_id));
                $this->outjson(array('code' => 304, 'msg' => '回复失败: 无法更新数据'));
            } else {
                /* 发送模板 */
                $cat_name = pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $order_data['cat_id']), 'cat_name');
                if (!empty($order_data['child_cat_id'])) {
                    $cat_name .= '-' . pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $order_data['child_cat_id']), 'cat_name');
                }
                $url = $_W['siteroot'] . 'app/' . $this->createMobileUrl('order', array('act' => 'replyDetail', 'order_id' => $order_data['order_id'], 'read' => 1));
                receive_msg($order_data['openid'], $cat_name, '', format($_W['timestamp'], 'Y年m月d日 H:i'), $url);
                $this->outjson(array('code' => 200, 'msg' => '回复成功'));
            }
        } else {
            $out['code'] = 304;
            $out['msg'] = '回复失败: 无法更新数据';
            $this->outjson($out);
        }

    }

    /*
     * 删除工单
     */
    public function delWordOrder() {
        global $_GPC, $_W;
        $order_data = pdo_get('wherein_knowledge_work_order', array('order_id' => $_GPC['order_id'], 'belong_to' => 0));
        if (empty($order_data)) {
            $this->outjson(array('code' => 404, 'msg' => '您要删除的数据不存在'));
        }
        if (pdo_delete('wherein_knowledge_work_order', array('order_id' => $order_data['order_id'], 'belong_to' => 0))) {
            //删除相关图片
            if (!empty($order_data['pic'])) {
                $pic = array();
                $pic = explode(IMG_IMPLODE, $order_data['pic']);
                foreach ($pic as $key => $value) {
                    if (file_exists(ATTACHMENT_ROOT . $value)) {
                        unlink(ATTACHMENT_ROOT . $value);
                    }
                }
            }
            $child_order_data = pdo_getall('wherein_knowledge_work_order', array('belong_to' => $order_data['order_id']), array('pic'));
            //删除下级
            if (pdo_delete('wherein_knowledge_work_order', array('belong_to' => $order_data['order_id']))) {
                if (!empty($child_order_data)) {
                    $child_pic = array();
                    foreach ($child_order_data as $k => $v) {
                        if (!empty($v['pic'])) {
                            $child_pic = explode(IMG_IMPLODE, $v['pic']);
                            foreach ($child_pic as $child_v) {
                                if (file_exists(ATTACHMENT_ROOT . $child_v)) {
                                    unlink(ATTACHMENT_ROOT . $child_v);
                                }
                            }
                        }
                    }
                }
            }
            $out['code'] = 200;
            $out['msg'] = '删除成功';
        } else {
            $out['code'] = 304;
            $out['msg'] = '删除失败';
        }
        $this->outjson($out);
    }

    /*
     * 导出工单
     */
    public function exportOrder() {
        global $_W,$_GPC;
        $order_status = !empty($_GPC['order_status']) ? $_GPC['order_status'] : 0;
        $where_sql = ' WHERE `uniacid`=:uniacid AND `order_status` = ' . $order_status . ' AND `belong_to` = 0 ';
        $where[':uniacid'] = $_W['uniacid'];

        $sortOrder = !empty($_GPC['sortOrder']) ? $_GPC['sortOrder'] : 'desc';
        $sortName = !empty($_GPC['sortName']) ? $_GPC['sortName'] : 'update_time DESC, add_time ';

        //搜索-分类
        if (!empty($_GPC['cat_id'])) {
            //查询当下有没有子分类
            $where_sql .= " AND `cat_id` = " . $_GPC['cat_id'];
        }
        //搜索-单号/客户名
        if (!empty($_GPC['search_name'])) {
            $where_sql .= " AND (`order_sn` LIKE :search_name  OR `nickname` LIKE :search_name) ";
            $where[':search_name'] = '%' . $_GPC['search_name'] . '%';
        }
        //搜索-时间
        if (!empty($_GPC['begin_time'])) {
            $begin_time = !empty($_GPC['begin_time']) ? strtotime($_GPC['begin_time']) : '';
            $where_sql .= " AND `add_time` >= " . $begin_time;
        }
        if (!empty($_GPC['end_time'])) {
            $end_time = !empty($_GPC['end_time']) ? strtotime($_GPC['end_time']) + + 24 * 60 * 60 : '';
            $where_sql .= " AND `add_time` <= " . $end_time;
        }
        $list = pdo_fetchall("SELECT order_id,order_sn,openid,nickname,content,pic,add_time,update_time,reply_num,customer_status,order_status FROM ".tablename('wherein_knowledge_work_order') . $where_sql . " ORDER BY " . $sortName . " " . $sortOrder, $where);

        $output = array();
        $pic = array();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $order_pic = array();
                $order_pic_str = '';
                if (!empty($value['pic']) && $_GPC['is_down_pic'] == '1') {
                    $order_pic = explode(IMG_IMPLODE, $value['pic']);
                    $pic[$value['order_id']] = $order_pic;
                    foreach ($order_pic as $k => $v) {
                        $ext = explode('.', $v);
                        $order_pic[$k] = $value['order_id'] . '_' . $k . '.' . $ext[count($ext)-1];
                    }
                    $order_pic_str = implode(';', $order_pic);
                }
                $output[] = array(
                    'order_sn' => $value['order_sn'],
                    'nickname' => $value['nickname'],
                    'reply_num' => $value['reply_num'],
                    'add_time' => format($value['add_time']),
                    'update_time' => !empty($value['update_time']) ? format($value['update_time']) : '',
                    'order_status_name' => $this->order_status[$value['order_status']],
                    'customer_status_name' => $this->customer_status[$value['customer_status']],
                    'content' => htmlspecialchars(strip_tags(str_replace(PHP_EOL, '', $value['content']))),//注意去除空格和换行
                    'pic' => $order_pic_str,
                );
            }
        }

        if ($_GPC['is_down_pic'] == '1') {
            //下载图片和工单

            /* 生成csv文件 */
            $file_name = 'order'.date('Ymd') . '.csv';
            $html = work_order_export_parse($output);//csv数据
            $path = "images/".intval($_W['uniacid'])."/" . date('Y/m/');
            mkdirs(ATTACHMENT_ROOT . '/' . $path);
            $csv_fullname = ATTACHMENT_ROOT . '/' . $path . $file_name;
            file_put_contents($csv_fullname, $html);

            /* 打包图片 */
            require_once KB_WEB . 'controller/zipfile.php';
            $dfile = tempnam('/tmp', 'tmp');//产生一个临时文件，用于缓存下载文件
            $zip = new zipfile();

            //以下是需要下载的图片数组信息，将需要下载的图片信息转化为类似即可
            $image = array();
            if (!empty($pic)) {
                foreach ($pic as $k => $v) {
                    foreach ($v as $kk => $vv) {
                        $ext = explode('.', $vv);
                        $image[] = array(
                            'image_src' => ATTACHMENT_ROOT . $vv,
                            'image_name' => 'image/' . $k.'_'.$kk . '.' . $ext[count($ext) - 1]
                        );
                    }
                }
            }
            //csv文件
            $csv_arr = array(
                'image_src' => $csv_fullname,
                'image_name' => $file_name,
            );
            $image[] = $csv_arr;

            foreach($image as $v){
                $zip->add_file(file_get_contents($v['image_src']), $v['image_name']);
            }

            $zip->output($dfile);

            // 下载文件
            $zipfilename = '工单' . date('YmdHis') . mt_rand(100,999) . '.zip'; //下载的默认文件名
            header('Pragma: public');
            header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
            header('Cache-Control:no-store, no-cache, must-revalidate');
            header('Cache-Control:pre-check=0, post-check=0, max-age=0');
            header('Content-Transfer-Encoding:binary');
            header('Content-Encoding:none');
            header('Content-type:multipart/form-data');
            header('Content-Disposition:attachment; filename="'.$zipfilename.'"'); //设置下载的默认文件名
            header('Content-length:'. filesize($dfile));
            $fp = fopen($dfile, 'r');
            while(connection_status() == 0 && $buf = @fread($fp, 8192)){
                echo $buf;
            }
            fclose($fp);
            @unlink($dfile);
            @unlink($csv_fullname);
            @flush();
            @ob_flush();
            exit();
        } else {
            //直接下载工单
            /* 生成csv文件 */
            $file_name = '导出工单'.date('Ymd') . '.csv';
            $html = work_order_export_parse($output);//csv数据
            header("Content-type:text/csv");
            header("Content-Disposition:attachment; filename=".$file_name);
            header('Cache-Control: max-age=0');
            echo $html;
            exit();
        }
    }

}